var student = require('../db/db')

exports.list=function(req,res){
	
    var pageSize = 5;                   //一页多少条
    var currentPage = req.query.currentPage;                //当前第几页
    var sort = {'_id':-1};        //排序（按登录时间倒序）
    var condition = {};                 //条件
    var skipnum = (currentPage - 1) * pageSize;   //跳过数
    
    student.find(condition).skip(skipnum).limit(pageSize).sort(sort).exec(function (err, data) {
        if (err) {
        	res.json({
				err_num:1,
				messages:"服务器忙，获取数据失败"
			})
        }else if(JSON.stringify(data) == '[]'){
        	res.json({
				err_num:2,
				messages:"没有更多数据了"
			})
        }else if(data){
          res.json({
				err_num:0,
				messages:data
			})
        }
    })
}

exports.index = function(req,res){
	
	res.render('student/index')
	
}

exports.add=function(req,res){
	res.render('student/add')
}


exports.addpost = function(req,res){
//	console.log(req.body)
	var stu = new student(req.body)
	
	stu.save((err,data)=>{
		if(err){
			res.json({
				err_num:1,
				messages:"服务器忙，请稍后重试"
			})
		}else{
			res.json({
				err_num:0,
				messages:data
			})
//			res.redirect('/student/')
		}
	})
	
}

exports.edit = function(req,res){
	var id = req.query.id
	student.findById(id, function(err, data){
        if (err) {
        	return res.json({
		        err_no: 500,
		        message: '读取数据失败，请稍后重试'
		      })
        }else if(data){
//      	console.log(data)
            res.render('student/edit',{
            	student:data
            })
        }
    })

}

exports.doedit = function(req,res){
	var id = req.query.id
	var updatastr = req.body
	console.log(updatastr)
	student.findByIdAndUpdate(id , updatastr , function(err, data){
        if (err) {
        	return res.json({
		        err_num: 1,
		        message: '读取数据失败，请稍后重试'
		      })
        }else if(data){
//      	console.log(data)
            return res.json({
		        err_num: 0,
		        message: data
		      })
        }
    })

}




exports.remove = function(req,res){
	var id = req.query.id
	console.log(id)
	student.findByIdAndRemove(id, function(err, data){
        if (err) {
        	return res.json({
		        err_num: 1,
		        message: '删除数据失败，请稍后重试'
		      })
        }else if(data){
//      	console.log(data)
           return res.json({
		        err_num: 0,
		        message: '删除数据成功'
		      })
        }
    })

}
